import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/models/server_model.dart';
import '../../../common/services/server_service.dart';
import '../../../common/utils/index.dart';

/// K8s Pod 信息
class K8sPod {
  final String name;
  final String namespace;
  final String status;
  final String restarts;
  final String age;
  final String ip;
  final String node;
  
  K8sPod({
    required this.name,
    required this.namespace,
    required this.status,
    required this.restarts,
    required this.age,
    this.ip = '',
    this.node = '',
  });
  
  bool get isRunning => status.toLowerCase().contains('running');
  bool get isPending => status.toLowerCase().contains('pending');
  bool get isFailed => status.toLowerCase().contains('error') || 
                       status.toLowerCase().contains('crashloop') ||
                       status.toLowerCase().contains('failed');
  
  /// 从 kubectl get pods 输出解析
  factory K8sPod.fromLine(String line, String namespace) {
    final parts = line.split(RegExp(r'\s+'));
    if (parts.length < 5) {
      return K8sPod(
        name: line,
        namespace: namespace,
        status: 'Unknown',
        restarts: '0',
        age: '',
      );
    }
    
    return K8sPod(
      name: parts[0],
      namespace: namespace,
      status: parts[2],
      restarts: parts[3],
      age: parts[4],
      ip: parts.length > 5 ? parts[5] : '',
      node: parts.length > 6 ? parts[6] : '',
    );
  }
}

/// K8s 命名空间信息
class K8sNamespace {
  final String name;
  final String status;
  final String age;
  
  K8sNamespace({
    required this.name,
    required this.status,
    required this.age,
  });
  
  bool get isActive => status.toLowerCase() == 'active';
  
  /// 从 kubectl get namespaces 输出解析
  factory K8sNamespace.fromLine(String line) {
    final parts = line.split(RegExp(r'\s+'));
    if (parts.length < 3) {
      return K8sNamespace(
        name: line,
        status: 'Unknown',
        age: '',
      );
    }
    
    return K8sNamespace(
      name: parts[0],
      status: parts[1],
      age: parts[2],
    );
  }
}

class ServerK8sController extends GetxController {
  final ServerService _serverService = Get.find<ServerService>();
  late final String serverId;
  
  Rx<ServerModel?> server = Rx<ServerModel?>(null);
  RxList<K8sPod> pods = <K8sPod>[].obs;
  RxList<K8sNamespace> namespaces = <K8sNamespace>[].obs;
  
  RxBool isLoading = false.obs;
  RxBool isRefreshing = false.obs;
  RxString errorMessage = ''.obs;
  RxBool hasKubectl = false.obs; // 是否安装了 kubectl
  
  // 安装状态
  RxBool isInstalling = false.obs;
  RxString installLog = ''.obs;
  RxDouble installProgress = 0.0.obs;
  bool _installCancelled = false;
  
  // 公开方法：检查是否已连接
  bool get isConnected => _serverService.isConnected(serverId);
  
  // 状态监听订阅
  StreamSubscription<ServerModel>? _stateSubscription;
  
  // 自动刷新定时器
  Timer? _refreshTimer;
  RxBool autoRefresh = false.obs;
  RxInt refreshInterval = 10.obs; // 刷新间隔（秒）
  
  // 命名空间过滤
  RxString selectedNamespace = 'default'.obs;
  RxBool showAllNamespaces = false.obs;
  
  // 分组显示
  RxBool groupByNamespace = true.obs;
  RxMap<String, bool> namespaceExpandedStates = <String, bool>{}.obs;

  @override
  void onInit() {
    super.onInit();
    debugPrint('🎬 ServerK8sController: onInit');
    
    serverId = Get.parameters['id'] ?? '';
    debugPrint('   服务器ID: $serverId');
    
    if (serverId.isEmpty) {
      debugPrint('❌ ServerK8sController: 服务器 ID 为空');
      LoadingUtil.error('服务器 ID 无效');
      Get.back();
      return;
    }
    
    _loadServer();
    _listenToServerStateChanges();
  }

  /// 监听服务器状态变化
  void _listenToServerStateChanges() {
    debugPrint('👂 ServerK8sController: 开始监听服务器状态变化');
    _stateSubscription = _serverService.watchServer(serverId).listen((updatedServer) {
      debugPrint('📢 ServerK8sController: 收到服务器状态更新 - ${updatedServer.name}');
      server.value = updatedServer;
    });
  }

  Future<void> _loadServer() async {
    debugPrint('📋 ServerK8sController: 加载服务器信息 - ID: $serverId');
    
    server.value = _serverService.getServer(serverId);
    if (server.value == null) {
      debugPrint('❌ ServerK8sController: 服务器不存在');
      LoadingUtil.error('服务器不存在');
      Get.back();
      return;
    }
    
    debugPrint('✅ ServerK8sController: 服务器信息加载成功');
    
    // 检查是否已连接
    if (_serverService.isConnected(serverId)) {
      await _checkKubectl();
      if (hasKubectl.value) {
        await loadNamespaces();
        await loadPods();
      }
    }
  }

  /// 检查是否安装了 kubectl
  Future<void> _checkKubectl() async {
    try {
      debugPrint('🔍 ServerK8sController: 检查 kubectl 是否可用');
      final client = _serverService.getClient(serverId);
      if (client == null) {
        hasKubectl.value = false;
        return;
      }
      
      final result = await client.run('which kubectl || where kubectl');
      final output = utf8.decode(result);
      
      hasKubectl.value = output.isNotEmpty && !output.contains('not found');
      debugPrint('✅ ServerK8sController: kubectl 可用性 - ${hasKubectl.value}');
    } catch (e) {
      debugPrint('❌ ServerK8sController: 检查 kubectl 失败 - $e');
      hasKubectl.value = false;
    }
  }

  /// 取消安装
  void cancelInstall() {
    _installCancelled = true;
    _appendLog('\n\n⚠️ 用户取消安装\n');
    isInstalling.value = false;
  }

  /// 安装 kubectl
  Future<void> installKubectl({bool useChinaMirror = true}) async {
    if (isInstalling.value) {
      LoadingUtil.info('正在安装中，请稍候...');
      return;
    }
    
    isInstalling.value = true;
    installLog.value = '';
    installProgress.value = 0.0;
    errorMessage.value = '';
    _installCancelled = false;
    
    try {
      debugPrint('🚀 ServerK8sController: 开始安装 kubectl');
      final client = _serverService.getClient(serverId);
      if (client == null) {
        throw Exception('未连接到服务器');
      }
      
      // 检测系统类型
      _appendLog('🔍 检测系统类型...\n');
      installProgress.value = 0.1;
      
      if (_installCancelled) return;
      
      final osResult = await client.run('cat /etc/os-release || uname');
      final osInfo = utf8.decode(osResult).toLowerCase();
      
      String installCommand;
      
      if (osInfo.contains('ubuntu') || osInfo.contains('debian')) {
        _appendLog('✅ 检测到 Ubuntu/Debian 系统\n');
        _appendLog(useChinaMirror ? '🚀 使用阿里云镜像加速\n\n' : '🌍 使用官方源\n\n');
        installCommand = useChinaMirror 
            ? _getUbuntuChinaMirrorScript() 
            : _getUbuntuInstallScript();
      } else if (osInfo.contains('centos') || osInfo.contains('rhel') || osInfo.contains('rocky')) {
        _appendLog('✅ 检测到 CentOS/RHEL 系统\n');
        _appendLog(useChinaMirror ? '🚀 使用阿里云镜像加速\n\n' : '🌍 使用官方源\n\n');
        installCommand = useChinaMirror 
            ? _getCentOSChinaMirrorScript() 
            : _getCentOSInstallScript();
      } else {
        _appendLog('✅ 使用通用安装方法\n\n');
        installCommand = _getGenericInstallScript(useChinaMirror);
      }
      
      installProgress.value = 0.2;
      
      if (_installCancelled) return;
      
      // 执行安装脚本
      _appendLog('📦 开始安装 kubectl (快速模式)...\n');
      _appendLog('提示: 如果下载慢，将自动使用国内镜像\n\n');
      _appendLog('--- 安装日志 ---\n');
      
      // 使用简单的 run 命令而不是 shell，更快更稳定
      _appendLog('执行安装命令...\n\n');
      
      final result = await client.run(installCommand).timeout(
        const Duration(minutes: 5),
        onTimeout: () {
          _appendLog('\n⏰ 安装超时，可能网络较慢\n');
          throw TimeoutException('安装超时');
        },
      );
      
      final output = utf8.decode(result);
      _appendLog(output);
      _appendLog('\n');
      
      installProgress.value = 0.9;
      _appendLog('\n--- 验证安装 ---\n');
      
      if (_installCancelled) return;
      
      // 验证安装
      await Future.delayed(const Duration(seconds: 1));
      await _checkKubectl();
      
      installProgress.value = 1.0;
      
      if (hasKubectl.value) {
        _appendLog('\n✅ kubectl 安装成功！\n');
        
        // 获取版本信息
        try {
          final versionResult = await client.run('kubectl version --client 2>&1 | head -1');
          final versionInfo = utf8.decode(versionResult).trim();
          _appendLog('\n版本信息:\n$versionInfo\n');
        } catch (e) {
          debugPrint('获取版本信息失败: $e');
        }
        
        LoadingUtil.success('kubectl 安装成功！');
        
        // 安装成功后加载数据
        if (!_installCancelled) {
          await Future.delayed(const Duration(milliseconds: 500));
          await loadNamespaces();
          await loadPods();
        }
      } else {
        _appendLog('\n❌ kubectl 安装失败，请检查日志\n');
        LoadingUtil.error('kubectl 安装失败');
      }
    } on TimeoutException {
      _appendLog('\n⏰ 安装超时，建议使用国内镜像重试\n');
      LoadingUtil.error('安装超时');
    } catch (e) {
      if (!_installCancelled) {
        debugPrint('❌ ServerK8sController: 安装 kubectl 失败 - $e');
        _appendLog('\n❌ 安装失败: $e\n');
        errorMessage.value = '安装失败: $e';
        LoadingUtil.error('安装失败: $e');
      }
    } finally {
      if (!_installCancelled) {
        isInstalling.value = false;
      }
    }
  }

  /// 添加日志
  void _appendLog(String log) {
    installLog.value += log;
    debugPrint('[INSTALL] $log');
  }

  /// 根据日志更新进度
  void _updateProgressFromLog(String log) {
    if (log.contains('download') || log.contains('下载')) {
      installProgress.value = 0.3;
    } else if (log.contains('install') || log.contains('安装')) {
      installProgress.value = 0.6;
    } else if (log.contains('complete') || log.contains('完成')) {
      installProgress.value = 0.8;
    }
  }

  /// 获取 Ubuntu/Debian 安装脚本（官方源）
  String _getUbuntuInstallScript() {
    return '''
if command -v snap &> /dev/null; then
    snap install kubectl --classic
else
    curl -LO "https://dl.k8s.io/release/\$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
    install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
    rm -f kubectl
fi
kubectl version --client
''';
  }

  /// 获取 Ubuntu/Debian 安装脚本（国内镜像）
  String _getUbuntuChinaMirrorScript() {
    return '''
# 使用阿里云镜像
echo "使用阿里云镜像下载..."
KUBECTL_VERSION=\$(curl -L -s https://mirrors.aliyun.com/kubernetes/latest.txt 2>/dev/null || echo "v1.28.4")
echo "版本: \$KUBECTL_VERSION"
curl -LO "https://mirrors.aliyun.com/kubernetes/\$KUBECTL_VERSION/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/kubectl 2>/dev/null || sudo mv kubectl /usr/local/bin/kubectl
echo "安装完成"
kubectl version --client
''';
  }

  /// 获取 CentOS/RHEL 安装脚本（官方源）
  String _getCentOSInstallScript() {
    return '''
curl -LO "https://dl.k8s.io/release/\$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
rm -f kubectl
kubectl version --client
''';
  }

  /// 获取 CentOS/RHEL 安装脚本（国内镜像）
  String _getCentOSChinaMirrorScript() {
    return '''
# 使用阿里云镜像
echo "使用阿里云镜像下载..."
KUBECTL_VERSION=\$(curl -L -s https://mirrors.aliyun.com/kubernetes/latest.txt 2>/dev/null || echo "v1.28.4")
echo "版本: \$KUBECTL_VERSION"
curl -LO "https://mirrors.aliyun.com/kubernetes/\$KUBECTL_VERSION/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/kubectl 2>/dev/null || sudo mv kubectl /usr/local/bin/kubectl
echo "安装完成"
kubectl version --client
''';
  }

  /// 获取通用安装脚本
  String _getGenericInstallScript(bool useChinaMirror) {
    if (useChinaMirror) {
      return '''
echo "使用阿里云镜像下载..."
KUBECTL_VERSION=\$(curl -L -s https://mirrors.aliyun.com/kubernetes/latest.txt 2>/dev/null || echo "v1.28.4")
echo "版本: \$KUBECTL_VERSION"
curl -LO "https://mirrors.aliyun.com/kubernetes/\$KUBECTL_VERSION/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/kubectl 2>/dev/null || sudo mv kubectl /usr/local/bin/kubectl
echo "安装完成"
kubectl version --client
''';
    } else {
      return '''
curl -LO "https://dl.k8s.io/release/\$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/kubectl 2>/dev/null || sudo mv kubectl /usr/local/bin/kubectl
kubectl version --client
''';
    }
  }

  /// 加载命名空间列表
  Future<void> loadNamespaces() async {
    try {
      debugPrint('📋 ServerK8sController: 加载命名空间列表');
      final client = _serverService.getClient(serverId);
      if (client == null) {
        throw Exception('未连接到服务器');
      }
      
      final result = await client.run('kubectl get namespaces --no-headers');
      final output = utf8.decode(result);
      
      final lines = output.split('\n')
          .where((line) => line.trim().isNotEmpty)
          .toList();
      
      namespaces.value = lines
          .map((line) => K8sNamespace.fromLine(line))
          .toList();
      
      debugPrint('✅ ServerK8sController: 加载了 ${namespaces.length} 个命名空间');
    } catch (e) {
      debugPrint('❌ ServerK8sController: 加载命名空间失败 - $e');
      errorMessage.value = '加载命名空间失败: $e';
    }
  }

  /// 加载 Pod 列表
  Future<void> loadPods() async {
    if (isRefreshing.value) return;
    
    isRefreshing.value = true;
    errorMessage.value = '';
    
    try {
      debugPrint('📋 ServerK8sController: 加载 Pod 列表');
      final client = _serverService.getClient(serverId);
      if (client == null) {
        throw Exception('未连接到服务器');
      }
      
      // 构建 kubectl 命令
      final namespace = showAllNamespaces.value ? '--all-namespaces' : '-n ${selectedNamespace.value}';
      final cmd = 'kubectl get pods $namespace --no-headers -o wide';
      
      debugPrint('   执行命令: $cmd');
      final result = await client.run(cmd);
      final output = utf8.decode(result);
      
      final lines = output.split('\n')
          .where((line) => line.trim().isNotEmpty)
          .toList();
      
      pods.value = lines
          .map((line) => K8sPod.fromLine(line, selectedNamespace.value))
          .toList();
      
      debugPrint('✅ ServerK8sController: 加载了 ${pods.length} 个 Pod');
    } catch (e) {
      debugPrint('❌ ServerK8sController: 加载 Pod 失败 - $e');
      errorMessage.value = '加载 Pod 失败: $e';
      LoadingUtil.error('加载 Pod 失败: $e');
    } finally {
      isRefreshing.value = false;
    }
  }

  /// 刷新数据
  Future<void> refreshData() async {
    if (!_serverService.isConnected(serverId)) {
      LoadingUtil.error('未连接到服务器');
      return;
    }
    
    if (!hasKubectl.value) {
      await _checkKubectl();
      if (!hasKubectl.value) {
        LoadingUtil.error('服务器未安装 kubectl');
        return;
      }
    }
    
    await loadNamespaces();
    await loadPods();
  }

  /// 切换命名空间
  void changeNamespace(String namespace) {
    selectedNamespace.value = namespace;
    showAllNamespaces.value = false;
    loadPods();
  }

  /// 切换显示所有命名空间
  void toggleShowAllNamespaces(bool value) {
    showAllNamespaces.value = value;
    loadPods();
  }

  /// 切换按命名空间分组
  void toggleGroupByNamespace(bool value) {
    groupByNamespace.value = value;
  }

  /// 切换命名空间展开状态
  void toggleNamespaceExpanded(String namespace) {
    namespaceExpandedStates[namespace] = !(namespaceExpandedStates[namespace] ?? true);
  }

  /// 判断命名空间是否展开
  bool isNamespaceExpanded(String namespace) {
    return namespaceExpandedStates[namespace] ?? true;
  }

  /// 切换自动刷新
  void toggleAutoRefresh(bool value) {
    autoRefresh.value = value;
    
    if (value) {
      _startAutoRefresh();
    } else {
      _stopAutoRefresh();
    }
  }

  /// 设置刷新间隔
  void setRefreshInterval(int seconds) {
    refreshInterval.value = seconds;
    if (autoRefresh.value) {
      _stopAutoRefresh();
      _startAutoRefresh();
    }
    LoadingUtil.info('刷新间隔已设置为 $seconds 秒');
  }

  /// 开始自动刷新
  void _startAutoRefresh() {
    _refreshTimer?.cancel();
    _refreshTimer = Timer.periodic(
      Duration(seconds: refreshInterval.value),
      (_) => loadPods(),
    );
    debugPrint('🔄 ServerK8sController: 自动刷新已启动 (${refreshInterval.value}秒)');
  }

  /// 停止自动刷新
  void _stopAutoRefresh() {
    _refreshTimer?.cancel();
    _refreshTimer = null;
    debugPrint('⏸️ ServerK8sController: 自动刷新已停止');
  }

  /// 获取 Pod 日志
  Future<void> showPodLogs(K8sPod pod) async {
    try {
      LoadingUtil.show('获取日志中...');
      
      final client = _serverService.getClient(serverId);
      if (client == null) {
        throw Exception('未连接到服务器');
      }
      
      final cmd = 'kubectl logs ${pod.name} -n ${pod.namespace} --tail=100';
      final result = await client.run(cmd);
      final logs = utf8.decode(result);
      
      LoadingUtil.dismiss();
      
      // 显示日志对话框
      Get.dialog(
        AlertDialog(
          title: Text('Pod 日志: ${pod.name}', style: const TextStyle(fontSize: 15)),
          content: SizedBox(
            width: double.maxFinite,
            height: 400,
            child: SingleChildScrollView(
              child: SelectableText(
                logs,
                style: const TextStyle(fontSize: 11, fontFamily: 'monospace'),
              ),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(),
              child: const Text('关闭'),
            ),
          ],
        ),
      );
    } catch (e) {
      LoadingUtil.error('获取日志失败: $e');
    }
  }

  /// 删除 Pod
  Future<void> deletePod(K8sPod pod) async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        title: const Text('确认删除', style: TextStyle(fontSize: 15)),
        content: Text('确定要删除 Pod "${pod.name}" 吗？', style: const TextStyle(fontSize: 12)),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        LoadingUtil.show('删除中...');
        
        final client = _serverService.getClient(serverId);
        if (client == null) {
          throw Exception('未连接到服务器');
        }
        
        await client.run('kubectl delete pod ${pod.name} -n ${pod.namespace}');
        LoadingUtil.success('删除成功');
        await loadPods();
      } catch (e) {
        LoadingUtil.error('删除失败: $e');
      } finally {
        LoadingUtil.dismiss();
      }
    }
  }

  /// 描述 Pod
  Future<void> describePod(K8sPod pod) async {
    try {
      LoadingUtil.show('获取详情中...');
      
      final client = _serverService.getClient(serverId);
      if (client == null) {
        throw Exception('未连接到服务器');
      }
      
      final result = await client.run('kubectl describe pod ${pod.name} -n ${pod.namespace}');
      final description = utf8.decode(result);
      
      LoadingUtil.dismiss();
      
      // 显示描述对话框
      Get.dialog(
        AlertDialog(
          title: Text('Pod 详情: ${pod.name}', style: const TextStyle(fontSize: 15)),
          content: SizedBox(
            width: double.maxFinite,
            height: 500,
            child: SingleChildScrollView(
              child: SelectableText(
                description,
                style: const TextStyle(fontSize: 11, fontFamily: 'monospace'),
              ),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(),
              child: const Text('关闭'),
            ),
          ],
        ),
      );
    } catch (e) {
      LoadingUtil.error('获取详情失败: $e');
    }
  }

  @override
  void onClose() {
    debugPrint('🔚 ServerK8sController: onClose');
    _stateSubscription?.cancel();
    _stopAutoRefresh();
    super.onClose();
  }
}

